﻿package cn.gdut.chengcai.base;

import java.io.FileOutputStream;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * @ClassName: Sendmail
 * @Description: 发送Email
 * @author: 谢
 * @date: 2016-2-27 上午9:06:55
 * 
 */
public class SendMail implements Runnable {

	/**
	 * @Message: run
	 * @Description: 继承Runnable接口，线程启动
	 * @author: 谢
	 */
	public void run() {
		String mail_host = "smtp.qq.com";
		String from_username = "1448925537@qq.com";
		String from_password = "1448925537xqh";
		String to_username = "xie_qing_hong@163.com";
		try {
			prepareMail(mail_host, from_username, from_password, to_username);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * @Message: prepareMail
	 * @Description: 初始化Mail的服务器和准备内容
	 * @author: 谢
	 * @param prop
	 * @param mail_host
	 * @param from_username
	 * @param from_password
	 * @param to_username
	 * @throws NoSuchProviderException
	 * @throws MessagingException
	 * @throws Exception
	 */
	public void prepareMail(String mail_host, String from_username, String from_password, String to_username)
			throws NoSuchProviderException, MessagingException, Exception {

		Properties prop = new Properties();
		prop.setProperty("mail.host", mail_host);
		prop.setProperty("mail.transport.protocol", "smtp");
		prop.setProperty("mail.smtp.auth", "true");

		// 使用JavaMail发送邮件的5个步骤
		// 1、创建session
		Session session = Session.getInstance(prop);
		// 开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
		session.setDebug(true);
		// 2、通过session得到transport对象
		Transport ts = session.getTransport();
		// 3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器
		// 用户名和密码都通过验证之后才能够正常发送邮件给收件人。
		ts.connect(mail_host, from_username, from_password);
		// 4、创建邮件（有不同方式）
		Message message = createAttachMail(session, from_username, to_username);
		// 5、发送邮件
		ts.sendMessage(message, message.getAllRecipients());
		ts.close();
	}

	/**
	 * @Method: createSimpleMail
	 * @Description: 创建一封只包含文本的邮件
	 * @Anthor:谢
	 * 
	 * @param session
	 * @param from_username
	 * @param to_username
	 * @return
	 * @throws Exception
	 */
	public MimeMessage createSimpleMail(Session session, String from_username, String to_username) throws Exception {
		// 创建邮件对象
		MimeMessage message = new MimeMessage(session);
		// 指明邮件的发件人
		message.setFrom(new InternetAddress(from_username));
		// 指明邮件的收件人，如果发件人和收件人是一样的，那就是自己给自己发
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(to_username));
		// 邮件的标题
		message.setSubject("只包含文本的简单邮件");
		// 邮件的文本内容
		message.setContent("你好啊！xieqinghong555", "text/html;charset=UTF-8");
		// 返回创建好的邮件对象
		return message;
	}

	/**
	 * @Method: createImageMail
	 * @Description: 生成一封邮件正文带图片的邮件
	 * @Anthor:谢
	 * 
	 * @param session
	 * @param from_username
	 * @param to_username
	 * @return
	 * @throws Exception
	 */
	public MimeMessage createImageMail(Session session, String from_username, String to_username) throws Exception {
		// 创建邮件
		MimeMessage message = new MimeMessage(session);
		// 设置邮件的基本信息
		// 发件人
		message.setFrom(new InternetAddress(from_username));
		// 收件人
		// message.setRecipient(Message.RecipientType.TO, new
		// InternetAddress(to_username));
		message.setRecipients(Message.RecipientType.TO, new Address[] { new InternetAddress(to_username) });
		// 邮件标题
		message.setSubject("带图片的邮件");

		// 准备邮件数据
		// 准备邮件正文数据
		MimeBodyPart text = new MimeBodyPart();
		text.setContent("这是一封邮件正文带图片<img src='cid:1.jpg'>的邮件", "text/html;charset=UTF-8");
		// 准备图片数据
		MimeBodyPart image = new MimeBodyPart();
		DataHandler dh = new DataHandler(new FileDataSource("src\\1.jpg"));
		image.setDataHandler(dh);
		image.setContentID("1.jpg");
		// 描述数据关系
		MimeMultipart mm = new MimeMultipart();
		mm.addBodyPart(text);
		mm.addBodyPart(image);
		mm.setSubType("related");

		message.setContent(mm);
		message.saveChanges();
		// 将创建好的邮件写入到E盘以文件的形式进行保存
		message.writeTo(new FileOutputStream("E:\\ImageMail.eml"));
		// 返回创建好的邮件
		return message;
	}

	/**
	 * @Method: createAttachMail
	 * @Description: 创建一封带附件的邮件
	 * @Anthor:谢
	 * 
	 * @param session
	 * @param from_username
	 * @param to_username
	 * @return
	 * @throws Exception
	 */
	public MimeMessage createAttachMail(Session session, String from_username, String to_username) throws Exception {
		MimeMessage message = new MimeMessage(session);

		// 设置邮件的基本信息
		// 发件人
		message.setFrom(new InternetAddress(from_username));
		// 收件人
		// message.setRecipient(Message.RecipientType.TO, new
		// InternetAddress(to_username));
		message.setRecipients(Message.RecipientType.TO, new Address[] { new InternetAddress(to_username) });
		// 邮件标题
		message.setSubject("JavaMail邮件发送测试");

		// 创建邮件正文，为了避免邮件正文中文乱码问题，需要使用charset=UTF-8指明字符编码
		MimeBodyPart text = new MimeBodyPart();
		text.setContent("使用JavaMail创建的带附件的邮件", "text/html;charset=UTF-8");

		// 创建邮件附件
		MimeBodyPart attach = new MimeBodyPart();
		DataHandler dh = new DataHandler(new FileDataSource("src\\职场会议满意度调查表.docx"));
		attach.setDataHandler(dh);
		// 解决附件中文名称乱码问题，利用MimeUtility.encodeText进行编码
		attach.setFileName(MimeUtility.encodeText(dh.getName()));

		// 创建容器描述数据关系
		MimeMultipart mp = new MimeMultipart();
		mp.addBodyPart(text);
		mp.addBodyPart(attach);
		mp.setSubType("mixed");

		message.setContent(mp);
		message.saveChanges();
		// 将创建的Email写入到E盘存储
		message.writeTo(new FileOutputStream("E:\\attachMail.eml"));
		// 返回生成的邮件
		return message;
	}

	/**
	 * @Method: createMixedMail
	 * @Description: 生成一封带附件和带图片的邮件
	 * @Anthor:谢
	 * 
	 * @param session
	 * @param from_username
	 * @param to_username
	 * @return
	 * @throws Exception
	 */
	public MimeMessage createMixedMail(Session session, String from_username, String to_username) throws Exception {
		// 创建邮件
		MimeMessage message = new MimeMessage(session);

		// 设置邮件的基本信息
		message.setFrom(new InternetAddress(from_username));
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(to_username));
		message.setSubject("带附件和带图片的的邮件");

		// 正文
		MimeBodyPart text = new MimeBodyPart();
		// text.setContent("这是我发送的3个附件！！！，请查收！","text/html;charset=UTF-8");
		text.setContent("<font color='red'>return这是一封邮件正文带图片！！！???<img src='cid:3.jpg'>的邮件</font>",
				"text/html;charset=UTF-8");

		// 图片
		MimeBodyPart image = new MimeBodyPart();
		DataHandler dh = new DataHandler(new FileDataSource("src\\3.jpg"));
		image.setDataHandler(dh);
		image.setContentID("3.jpg");

		// 附件1
		MimeBodyPart attach1 = new MimeBodyPart();
		DataHandler dh1 = new DataHandler(new FileDataSource("src\\temp.pdf"));
		attach1.setDataHandler(dh1);
		attach1.setFileName(MimeUtility.encodeText(dh1.getName()));

		// 附件2
		MimeBodyPart attach2 = new MimeBodyPart();
		DataHandler dh2 = new DataHandler(new FileDataSource("src\\dom4j-1.6.1.jar"));
		attach2.setDataHandler(dh2);
		attach2.setFileName(MimeUtility.encodeText(dh2.getName()));

		// 描述关系:正文和图片
		MimeMultipart mp = new MimeMultipart();
		mp.addBodyPart(text);
		mp.addBodyPart(image);
		mp.setSubType("related");

		// 描述关系:正文和附件
		MimeMultipart mp2 = new MimeMultipart();
		mp2.addBodyPart(attach1);
		mp2.addBodyPart(attach2);

		// 代表正文的bodypart
		MimeBodyPart content = new MimeBodyPart();
		content.setContent(mp);
		mp2.addBodyPart(content);
		mp2.setSubType("mixed");

		message.setContent(mp2);
		message.saveChanges();
		message.writeTo(new FileOutputStream("E:\\MixedMail.eml"));

		// 返回创建好的的邮件
		return message;
	}
}